package com.beatingapp;

import java.io.IOException;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.modifier.PathModifier;
import org.andengine.entity.modifier.PathModifier.Path;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.debug.Debug;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.Toast;

import com.beatingapp.clases.Imagen;

public class CigarrilloActivity extends SimpleBaseGameActivity implements IUpdateHandler
{

	private final static int CAMERA_WIDTH = 800;

	private final static int CAMERA_HEIGHT = 480;	

	private Camera camera;

	private BitmapTextureAtlas fondoTexture;
	
	private BitmapTextureAtlas BarraTiempoTextureAtlas;
	
	private ITextureRegion BarraTiempo;
	
	private Sprite barraSprite;

	private BitmapTextureAtlas mBitmapTextureAtlas, cigarrilloTextureAtlas, cenizaTextureAtlas, infoTextureAtlas;

	private BitmapTextureAtlas vidasTextureAtlas, sinVidasTextureAtlas;

	private ITextureRegion fondoTextureRegion, cenizaTextureRegion, cigarrilloTextureRegion, fuegoTextureRegion, infoTextureRegion, vidaTextureRegion, sinVidaTextureRegion;

	private Imagen cenizaSprite, fuegoSprite;

	private Sprite cigarrilloSprite;

	private Font font;

	private int intentos;

	private Sound mGameOverSound, mColisionSound, winSound;

	private Scene scene, scenaInfo;

	private PathModifier pathModifier;

	private boolean corrriendo;

	private int salir = 0;

	private int tiempo =0;

	private Sprite[] vidas;

	private Sprite[] sinvidas;

	@Override
	public EngineOptions onCreateEngineOptions( )
	{
		Toast.makeText( getApplicationContext(), "Evita que el fuego toque el cigarrillo!\nToca la pantalla para empezar", Toast.LENGTH_SHORT ).show( );

		camera = new Camera( 0, 0, CAMERA_WIDTH, CAMERA_HEIGHT );
		EngineOptions engineOptions = new EngineOptions( true, ScreenOrientation.LANDSCAPE_SENSOR,
				new FillResolutionPolicy(), camera );
		engineOptions.getAudioOptions( ).setNeedsSound( true );
		return engineOptions;
	}

	@Override
	protected void onCreateResources( )
	{
		intentos = getIntent().getExtras().getInt("Vidas");
		
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath( "gfx/actividadCigarrillo/" );

		// cargando el fondo
		this.fondoTexture = new BitmapTextureAtlas( this.getTextureManager( ), 1024, 512 );
		this.fondoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.fondoTexture, this, "fondo.jpg", 0, 0 );
		this.fondoTexture.load( );

		// cargando fuego y cigarrillo
		this.mBitmapTextureAtlas = new BitmapTextureAtlas( getTextureManager( ), 118, 123, TextureOptions.DEFAULT );
		this.fuegoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBitmapTextureAtlas, this, "fuego.png", 0, 0 );
		this.mBitmapTextureAtlas.load();

		cigarrilloTextureAtlas = new BitmapTextureAtlas( getTextureManager( ), 317, 501, TextureOptions.DEFAULT );		
		this.cigarrilloTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				cigarrilloTextureAtlas, this, "mano.png", 0, 0 );
		cigarrilloTextureAtlas.load( );

		cenizaTextureAtlas = new BitmapTextureAtlas( getTextureManager( ), 22, 22, TextureOptions.DEFAULT );		
		this.cenizaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				cenizaTextureAtlas, this, "ceniza.png", 0, 0 );
		cenizaTextureAtlas.load( );

		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath( "gfx/vidas/" );

		//vidas
		this.vidasTextureAtlas = new BitmapTextureAtlas( this.getTextureManager( ), 60, 60 );
		this.vidaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.vidasTextureAtlas, this, "vida.png", 0, 0 );
		this.vidasTextureAtlas.load( );

		this.sinVidasTextureAtlas = new BitmapTextureAtlas( this.getTextureManager( ), 60, 60 );
		this.sinVidaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.sinVidasTextureAtlas, this, "sinVida.png", 0, 0 );
		this.sinVidasTextureAtlas.load( );
		
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath( "gfx/" );
		
		this.BarraTiempoTextureAtlas = new BitmapTextureAtlas( this.getTextureManager( ), 800, 30 );
		BarraTiempo=BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.BarraTiempoTextureAtlas, this, "barra.png", 0, 0);
		this.BarraTiempoTextureAtlas.load();
		
		try
		{
			// cargando sonido colision
			SoundFactory.setAssetBasePath( "mfx/" );
			this.mColisionSound = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this,
					"colision.ogg" );
			this.mGameOverSound = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"game_over.ogg" );
			this.winSound = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"win.ogg" );
		}
		catch ( IOException e )
		{
			Debug.e( e );
		}

		// cargando fuente
		this.font = FontFactory.create( this.getFontManager( ), this.getTextureManager( ), 256,
				256, Typeface.create( Typeface.DEFAULT, Typeface.BOLD ), 32 );
		this.font.load( );
	}

	@Override
	protected Scene onCreateScene( )
	{
		crearEscenaJuego( );
		return scene;
	}

	private void crearEscenaJuego()
	{
		scene = new Scene( );
		scene.setBackgroundEnabled( false );
		
		barraSprite = new Sprite (0,0, this.BarraTiempo, this.getVertexBufferObjectManager());
		barraSprite.setVisible(false);
		
		Sprite fondoSprite = new Sprite( 0, 0, fondoTextureRegion, new VertexBufferObjectManager( ) );

		fuegoSprite = new Imagen( CAMERA_WIDTH / 2, 0, fuegoTextureRegion, new VertexBufferObjectManager( ) );

		scene.attachChild( fondoSprite );
		scene.attachChild(barraSprite);
		scene.attachChild( fuegoSprite );
		
		mEngine.enableVibrator(getApplicationContext());
		scene.setOnSceneTouchListener( new IOnSceneTouchListener() 
		{

			@Override
			public boolean onSceneTouchEvent(Scene arg0, TouchEvent pSceneTouchEvent) 
			{
				switch ( pSceneTouchEvent.getAction( ) )
				{
				case TouchEvent.ACTION_DOWN:
					if( !corrriendo )
					{		
						barraSprite.setVisible(true);
						Path path = new Path( 2 ).to(-800, 0).to(0, 0);
						pathModifier = new PathModifier( 20, path);
						barraSprite.registerEntityModifier( pathModifier );
						
						Timer t = new Timer();  

						TimerTask task = new TimerTask() {  

							@Override  
							public void run() {  
								runOnUiThread(new Runnable() {  

									@Override  
									public void run() 
									{  		      
										if( tiempo < 10000 )
										{
											Path path = null;
											if( tiempo%200 == 0 )
											{
												path = new Path( 4 ).to(fuegoSprite.getX( ), fuegoSprite.getY( ) ).
														to(cenizaSprite.getX( )+2, cenizaSprite.getY( ) );
												Random random = new Random( );
												int x2 = random.nextInt( ( int ) ( CAMERA_WIDTH - fuegoSprite.getWidth( ) ) );
												int y2 = random.nextInt( ( int ) ( CAMERA_HEIGHT - fuegoSprite.getHeight( ) ) );	
												path.to(x2, y2 );
												path.to(cenizaSprite.getX( )+2, cenizaSprite.getY( ) );
											}
											else
											{
												Random random = new Random( );
												path = new Path( 4 );
												path.to(fuegoSprite.getX( ), fuegoSprite.getY( ) );
												for ( int i = 0; i < 2; i++ )
												{
													int x2 = random.nextInt( ( int ) ( CAMERA_WIDTH - fuegoSprite.getWidth( ) ) );
													int y2 = random.nextInt( ( int ) ( CAMERA_HEIGHT - fuegoSprite.getHeight( ) ) );	
													path.to(x2, y2 );
												}
												path.to(cenizaSprite.getX( )+2, cenizaSprite.getY( ) );
											}

											pathModifier = new PathModifier( 2, path );
											fuegoSprite.registerEntityModifier( pathModifier );										

											tiempo += 1000;
										}
										else
										{
											if(corrriendo)
											{
												cigarrilloSprite.setPosition( CAMERA_WIDTH / 2, CAMERA_HEIGHT - cigarrilloSprite.getHeight( ) );
												corrriendo = false;
												if( !winSound.isReleased() )
													winSound.play();
												crearEscenaFin( false );
											}
										}
									}  
								});  
							}  
						};  

						t.scheduleAtFixedRate(task, 0, 2000);


						int x = ( int ) Math.ceil( pSceneTouchEvent.getX( ) - cigarrilloTextureRegion.getWidth( )/2 );
						int y = ( int ) Math.ceil( pSceneTouchEvent.getY( )  - cigarrilloTextureRegion.getHeight( )/2);


						cenizaSprite = new Imagen( pSceneTouchEvent.getX( ) + 32, pSceneTouchEvent.getY( ) - 200, cenizaTextureRegion,
								new VertexBufferObjectManager( ) );

						cigarrilloSprite = new Sprite( x, y, cigarrilloTextureRegion,
								new VertexBufferObjectManager( ) )
						{
							@Override
							public boolean onAreaTouched( TouchEvent pSceneTouchEvent, float pTouchAreaLocalX,
									float pTouchAreaLocalY )
							{
								if( corrriendo  )
								{
									this.setPosition( pSceneTouchEvent.getX( ) - this.getWidth( ) / 2,
											(pSceneTouchEvent.getY( ) - this.getHeight( ) / 2)-60 );
									cenizaSprite.setX( pSceneTouchEvent.getX( ) + 32 );
									cenizaSprite.setY( pSceneTouchEvent.getY( ) - 200 );
									return true;
								}
								else 
									return false;
							}
						};
						scene.attachChild( cigarrilloSprite );
						scene.attachChild( cenizaSprite );
						scene.registerTouchArea( cigarrilloSprite );

						scene.reset( );				
						corrriendo = true;

					}
					return true;

				default:
					return false;
				}
			}
		} );
		scene.registerUpdateHandler( this );	
		
		vidas = new Sprite[3];
		sinvidas = new Sprite[3];
		
		for ( int i = 0; i < intentos; i++ )
		{
			vidas[i] = new Sprite( (60*(i)) + 3, 32, vidaTextureRegion, new VertexBufferObjectManager( ) );
			scene.attachChild( vidas[i] );
		}
		for ( int i = intentos; i < 3; i++ )
		{
			sinvidas[i] = new Sprite( (60*(i)) + 3, 32, sinVidaTextureRegion, new VertexBufferObjectManager( ) );
			scene.attachChild( sinvidas[i] );
		}

		scene.setTouchAreaBindingOnActionDownEnabled( true );		
		corrriendo = false;
	}


	private void crearEscenaFin( final boolean pierde )
	{	
		barraSprite.setVisible(false);
		if( pierde )
			BitmapTextureAtlasTextureRegionFactory.setAssetBasePath( "gfx/" );
		else
			BitmapTextureAtlasTextureRegionFactory.setAssetBasePath( "gfx/actividadCigarrillo/" );

		String ruta = pierde ? "queMal.png" : "fin.png";

		infoTextureAtlas = new BitmapTextureAtlas( getTextureManager( ), 800, 480 );
		infoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( 
				infoTextureAtlas, this, ruta, 0, 0 );
		infoTextureAtlas.load( );			

		scenaInfo = new Scene( );

		Sprite sprite = new Sprite( 0, 0, infoTextureRegion, new VertexBufferObjectManager( ));

		scenaInfo.attachChild( sprite );
		scene.setChildScene( scenaInfo, true, true, true );

		Timer t = new Timer();  

		TimerTask task = new TimerTask() {  

			@Override  
			public void run() {  
				runOnUiThread(new Runnable() {  

					@Override  
					public void run() 
					{  		      
						if( salir == 0 )
						{
							try 
							{
								Thread.sleep(5000);
							} 
							catch (InterruptedException e) 
							{
								e.printStackTrace();
							}

							if( !pierde )
							{
								Intent intent = new Intent(CigarrilloActivity.this, FelicidadesActivity.class);
								Bundle b = new Bundle( );
								b.putInt( "Vidas", intentos );
								intent.putExtras( b );
								startActivity(intent);
							}
							CigarrilloActivity.this.finish( );
							salir++;
						}
					}  
				});  
			}  
		};  

		t.scheduleAtFixedRate(task, 0, 1000);		
	}

	private void colisionConFuego( )
	{
		if(cenizaSprite != null)
		{
			if ( cenizaSprite.collidesWith( fuegoSprite ) )
			{
				if ( !cenizaSprite.estaEnColision( ) )
				{
					cenizaSprite.setEstaEnColision( true );
					intentos--;
					mEngine.vibrate(100);

					vidas[intentos].setVisible(false);
					sinvidas[intentos] = new Sprite( (60*(intentos)) + 3, 32, sinVidaTextureRegion, new VertexBufferObjectManager( ) );
					sinvidas[intentos].setVisible(true);

					scene.attachChild( sinvidas[intentos] );

					mColisionSound.play();
					if( intentos == 0 )
					{		
						mGameOverSound.play( );
						corrriendo = false;
						fuegoSprite.clearEntityModifiers( );
						fuegoSprite.setPosition( CAMERA_WIDTH / 2, 0 );
						cigarrilloSprite.setPosition( CAMERA_WIDTH / 2, CAMERA_HEIGHT - cigarrilloSprite.getHeight( ) );	
						crearEscenaFin( true );
					}
				}
			}
			else
			{
				cenizaSprite.setEstaEnColision( false );
			}
		}
	}

	@Override
	public void onUpdate( float arg0 )
	{
		colisionConFuego( );
	}

	@Override
	public void reset( )
	{

	}

}
